<template>
    <van-form @submit="onSubmit">
        <van-cell-group inset>
            <van-field
                v-model="msg"
                name="验证码"
                label="验证码"
                placeholder="验证码"
                :rules="[{ required: true, message: '请填写验证码' }]"
            >
                <template #button>
                    <van-button 
                    @click="getMsg" 
                    size="small"
                    :disabled="btnTime !== 5"
                >
                    {{ btnText }}</van-button>
                </template>
            </van-field>
        </van-cell-group>
        <div style="margin: 16px">
            <van-button 
                :disabled="btnFlag"
                round 
                block 
                type="primary" 
                native-type="submit"
            >
                提交验证码
            </van-button>
        </div>
    </van-form>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import type { Ref } from 'vue'
import { dosendmsgcode, docheckcode } from "@/api/register";
import { showSuccessToast, showFailToast } from 'vant';
import { useRouter } from "vue-router";

// 创建一个 选项式 API 中的 this.$router
const router = useRouter()

// 存储用户输入的验证码
const msg: Ref<string> = ref('')

// 提交验证码
async function onSubmit() {
    const { data } = await docheckcode({
        tel: window.localStorage.getItem('phoneNum') + '',
        telcode: msg.value
    })
    if (data.code !== '200') {
        // 提示用户验证码错误
        return showFailToast(data.message);
    }

    // 提醒用户验证码通过
    showSuccessToast(data.message);

    //跳转第三个页面
    router.push('/register/no3')
}

// 获取验证码
const btnTime: Ref<number> = ref(5)
const btnText: Ref<string> = ref('获取验证码')

async function getMsg() {
    btnText.value = '5s 后重新获取验证码'
    btnTime.value--

    const timerId = setInterval(() => {
        btnText.value = `${btnTime.value}s 后重新获取验证码`
        btnTime.value--

        if (btnTime.value === -1) {
            clearInterval(timerId)

            btnText.value = '获取验证码'
            btnTime.value = 5
        }
    }, 1000)

    const { data } = await dosendmsgcode({
        tel: window.localStorage.getItem('phoneNum') + ''
    })

    // console.log(data);

    msg.value = data.data    
}

// 侦听验证码, 控制 提交验证码 按钮能否使用
const btnFlag: Ref<boolean> = ref(true)
watch(
    msg,
    () => {
        btnFlag.value = msg.value.length !== 5
    },
    {
        immediate: true
    }
)
</script>